/*
 *  Copyright 2019-2020 Zheng Jie
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package me.zhengjie.modules.system.rest;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import me.zhengjie.annotation.Log;
import me.zhengjie.exception.BadRequestException;
import me.zhengjie.modules.system.domain.Role;
import me.zhengjie.modules.system.service.MenuService;
import me.zhengjie.modules.system.service.RoleService;
import me.zhengjie.modules.system.service.dto.RoleQueryCriteria;
import me.zhengjie.modules.system.service.dto.RoleSmallDto;
import me.zhengjie.utils.SecurityUtils;
import me.zhengjie.utils.enums.DataScopeEnum;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Zheng Jie
 * @date 2018-12-03
 */
@RestController
@RequiredArgsConstructor
@Api(tags = "系统：集团角色管理")
@RequestMapping("/api/corporationRoles")
public class CorporationRoleController {

    private final RoleService roleService;
    private final MenuService menuService;

    private static final String ENTITY_NAME = "role";

    @Log("查询角色")
    @ApiOperation("查询角色")
    @GetMapping
    public ResponseEntity<Object> query(RoleQueryCriteria criteria, Pageable pageable){
        criteria.setCorporationCode(SecurityUtils.getCorporationCode());
        return new ResponseEntity<>(roleService.queryAll(criteria,pageable),HttpStatus.OK);
    }

    @ApiOperation("返回全部的角色-用户编辑页使用")
    @GetMapping(value = "/all")
    public ResponseEntity<Object> all(){
        RoleQueryCriteria criteria = new RoleQueryCriteria();
        criteria.setCorporationCode(SecurityUtils.getCorporationCode());
        return new ResponseEntity<>(roleService.queryAll(criteria),HttpStatus.OK);
    }

    @Log("新增角色")
    @ApiOperation("新增角色")
    @PostMapping
    @PreAuthorize("@el.check('corporationRoles:add')")
    public ResponseEntity<Object> create(@Validated @RequestBody Role resources){
        if (resources.getId() != null) {
            throw new BadRequestException("A new "+ ENTITY_NAME +" cannot already have an ID");
        }
        List<Integer> levels = roleService.findByUsersId(SecurityUtils.getCurrentUserId()).stream().map(RoleSmallDto::getLevel).collect(Collectors.toList());
        int min = Collections.min(levels);
        resources.setLevel(min + 1);
        resources.setDataScope(DataScopeEnum.ALL.getValue());
        resources.setCorporationCode(SecurityUtils.getCorporationCode());
        roleService.create(resources);
        return new ResponseEntity<>(HttpStatus.CREATED);
    }

    @Log("修改角色")
    @ApiOperation("修改角色")
    @PutMapping
    @PreAuthorize("@el.check('corporationRoles:edit')")
    public ResponseEntity<Object> update(@Validated(Role.Update.class) @RequestBody Role resources){
        List<Integer> levels = roleService.findByUsersId(SecurityUtils.getCurrentUserId()).stream().map(RoleSmallDto::getLevel).collect(Collectors.toList());
        int min = Collections.min(levels);
        resources.setLevel(min + 1);
        resources.setDataScope(DataScopeEnum.ALL.getValue());
        resources.setCorporationCode(SecurityUtils.getCorporationCode());
        roleService.update(resources);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @ApiOperation("返回全部的菜单")
    @GetMapping(value = "/lazy")
    public ResponseEntity<Object> lazy(){
        return new ResponseEntity<>(menuService.getCorporationMenus(),HttpStatus.OK);
    }
}
